package com.bw.service;

import com.alibaba.fastjson.JSON;
import com.bw.dao.GoodsDao;
import com.bw.pojo.Goods;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/***************************
 FileAction:

 CreateTime:2022-08-01 13:36
 Author:Aaking-aline
 ****************************/
@Service
public class GoodsService {
	@Autowired
	private GoodsDao goodsDao;

	// 当前业务层 需要处理三件事
	public void insertGoods(Goods goods, MultipartFile file) throws IOException {
		// 第一件事 更新goods对象中的 图片路径
		String path = "/synthesize_review_war_exploded/upload/" + file.getOriginalFilename();
		goods.setGoods_img(path);

		// 第二件 把前端发过来的文件 写入磁盘内
		File file1 = new File("D:/D-regional-project/java-project/2007A开发专业四/synthesize_review/out/artifacts/synthesize_review_war_exploded/upload/" + file.getOriginalFilename());
		file.transferTo(file1);

		// 第三件 把前端发过来所有的商品信息写入到数据库
		goodsDao.insertGoods(goods);
	}


	@SneakyThrows
	public void selectAllGoods() {
		List<Goods> list = goodsDao.selectAllGoods();

		String json = JSON.toJSONString(list);

		File file = new File("D:/exam/json.txt");
		FileWriter fw = new FileWriter(file);
		fw.write(json);

		fw.close();
	}

	public String selectPageGoods(String page, int number) {

		int index = (Integer.parseInt(page) - 1) * number;

		List<Goods> list = goodsDao.selectPageGoods(index,number);

		return JSON.toJSONString(list);
	}

	public String getPageNum() {
		Integer pageNum = goodsDao.getPageNum();

		double ceil = Math.ceil(pageNum / 5.0);

		return ceil + "";
	}

	public void deleteGoods(String id) {
		goodsDao.deleteGoods(id);
	}

	public void updateGoods(Goods goods, MultipartFile file) throws IOException {
		// 第一件事 更新goods对象中的 图片路径
		String path = "/synthesize_review_war_exploded/upload/" + file.getOriginalFilename();
		goods.setGoods_img(path);

		// 第二件 把前端发过来的文件 写入磁盘内
		File file1 = new File("D:/D-regional-project/java-project/2007A开发专业四/synthesize_review/out/artifacts/synthesize_review_war_exploded/upload/" + file.getOriginalFilename());
		file.transferTo(file1);

		// 第三件 把前端发过来所有的商品信息写入到数据库
		goodsDao.updateGoods(goods);
	}

	public String selectGoodsByPrice(String a0, String a1) {
		List<Goods> list = goodsDao.selectGoodsByPrice(a0,a1);
		return JSON.toJSONString(list);
	}
}
